import '@wangeditor/editor/dist/css/style.css'
import {useEffect, useState} from 'react'
import {Editor, Toolbar} from '@wangeditor/editor-for-react'
import {BASE_URL} from "@utils/constants.js";
import {api_file_upload} from "@utils/api.js";
import styles from './index.module.less'

export default (props) => {
    const {value, onChange} = props
    const [editor, setEditor] = useState()
    const editorConfig = {
        placeholder: '请输入内容...',
        MENU_CONF: {
            uploadImage: {
                fieldName: 'file',
                server: `${BASE_URL}${api_file_upload}`,
                headers: {
                    token: localStorage.getItem('token') || '',
                },
                customInsert(res, insertFn) {
                    insertFn(res?.body?.path.startsWith('http') ? res?.body?.path : BASE_URL + res?.body?.path)
                }
            },
            uploadVideo: {
                fieldName: 'file',
                server: `${BASE_URL}${api_file_upload}`,
                headers: {
                    token: localStorage.getItem('token') || '',
                },
                customInsert(res, insertFn) {
                    insertFn(res?.body?.path.startsWith('http') ? res?.body?.path : BASE_URL + res?.body?.path)
                }
            }
        }
    }
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor['destroy']()
            setEditor(null)
        }
    }, [editor])
    return (
        <div className={styles.editor} style={{border: '1px solid #ccc', zIndex: 100}}>
            <Toolbar
                editor={editor}
                defaultConfig={{}}
                mode="default"
                style={{borderBottom: '1px solid #ccc'}}
            />
            <Editor
                defaultConfig={editorConfig}
                value={value}
                onCreated={(e) => {
                    setTimeout(() => {
                        setEditor(e)
                    }, 0)
                }}
                onChange={editor => onChange?.(editor.getHtml())}
                mode="default"
                style={{height: '300px', overflowY: 'hidden'}}
            />
        </div>
    )
}